from IPy import IP
from django.db import models
from django.utils import timezone


def checkip(data):
      try:
        IP(data).version()
      except Exception as e:
        return False
      return True

class Zone(models.Model):
    status_choice = (
        (1, '激活'),
        (0, '暂停解析')
        )
    zone = models.CharField(max_length=255, unique=True,verbose_name='域名')
    comment = models.TextField(max_length=128, default='', blank=True, verbose_name='描述')
    status = models.SmallIntegerField(choices=status_choice, default=1, verbose_name='状态')
    gmt_create = models.DateTimeField(default=timezone.now,verbose_name='创建时间')

    def get_items(self):
        return self.dnsrecord_set.all().count()
    get_items.short_description = '解析数'
    
    def __str__(self):
        return self.zone
    class Meta:
        db_table = 'dns_zones'
        verbose_name = "domian"
        verbose_name_plural = verbose_name


class DnsRecord(models.Model):
    type_choice = (
        ('A', 'A记录:　将域名指向一个IP地址'),
        ('CNAME', 'CNAME:　将域名指向另一个域名'),
        ('MX', 'MX:　设置邮箱,添加MX记录'),
        ('TXT', 'TXT:　长度限制255，通常用来做SPF记录'),
        ('NS', 'NS:　域名服务器记录，将子域名交给其他服务商解析'),
        ('AAAA', 'AAAA:　将主机名指向IPv6地址'),
        ('SRV', 'SRV:  记录哪台计算机提供了哪个服务，如：_xmpp-server._tcp'),
    )
    host = models.CharField(max_length=255,verbose_name='主机记录')
    type = models.CharField(choices=type_choice, max_length=5, default='A',verbose_name='记录类型')
    data = models.CharField(max_length=255, blank=True, null=True,verbose_name='记录值')
    ttl = models.IntegerField(verbose_name='TTL(秒)', default=60)
    zone = models.ForeignKey(
        Zone,on_delete=models.CASCADE,verbose_name='域名')
    mx_priority = models.IntegerField(blank=True, null=True)
    refresh = models.IntegerField(default=3600)
    retry = models.IntegerField(default=3600)
    expire = models.IntegerField(default=86400)
    minimum = models.IntegerField(default=3600)
    serial = models.BigIntegerField(default=2016111600)
    resp_person = models.CharField(max_length=64, default="ns1.ops.net")
    primary_ns = models.CharField(max_length=64, default="ns1.ops.net")
    gmt_create = models.DateTimeField(default=timezone.now,verbose_name='创建时间')
    gmt_modified = models.DateField(auto_now=True,verbose_name='最后操作时间')

    def save(self, *args, **kwargs):
        res = checkip(self.data)
        if  res == 0 and self.data[-1] != "." and self.type=="CNAME":
          self.data = '{}{}'.format(self.data, '.')
        super(DnsRecord, self).save(*args, **kwargs)

    def __str__(self):
        return self.host
    class Meta:
        db_table = 'dns_records'
        verbose_name = "record"
        verbose_name_plural = verbose_name
        ordering = ['-gmt_modified']
